package com.af.security.auth.user.data;

import com.af.security.auth.user.detail.AuthClient;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : zhenyun.su
 * @comment : 获取oauth认证数据，可公共
 * @since : 2020-10-16
 */

public class AfOauthHolder extends AfAuthHolder {

    public AfOauthHolder() {
    }

    public OAuth2Request getOAuth2Request() {
        if (isAuthenticated() && (getAuthentication() instanceof OAuth2Authentication)) {
            OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) getAuthentication();
            return oAuth2Authentication.getOAuth2Request();
        }
        return null;
    }

    public String getClientId() {
        if (getOAuth2Request() != null) {
            return getOAuth2Request().getClientId();
        }
        return null;
    }

    public String getGrantType() {
        if (getOAuth2Request() != null) {
            return getOAuth2Request().getGrantType();
        }
        return null;
    }

    public AuthClient getAuthClient(ClientDetailsService clientDetailsService) {
        OAuth2Request oAuth2Request = getOAuth2Request();
        if (oAuth2Request != null) {
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(oAuth2Request.getClientId());
            if (clientDetails != null) {
                AuthClient authClient = new AuthClient();
                authClient.setId(clientDetails.getClientId());
                authClient.setName(clientDetails.getClientId());
                Map<String, Object> attributes = new HashMap<>();
                clientDetails.getAdditionalInformation().forEach((k, v) -> {
                    attributes.put(k, v);
                    if ("description".equalsIgnoreCase(String.valueOf(k))) {
                        authClient.setDescription(String.valueOf(v));
                    }
                });
                authClient.setExtendedAttributes(attributes);
                return authClient;
            }
        }
        return null;
    }
}
